using System.ServiceModel;

using BLToolkit.Aspects;
using BLToolkit.Reflection;

using EMan.Common;
using EMan.Common.EnterpriseStructure;

using TrueCode.Core.Aspects;

namespace EMan.WCF
{
  [ Mixin(typeof( IEnterpriseStructure ), "Proxy", true )]
  [ Mixin(typeof( IEMan ), "Proxy", true )]
  public abstract class EManServiceProxy
  {
    private readonly object _proxyAccess = new object();
    private EManWCFClient _proxy;

    [UsedImplicitly]
    protected IEnterpriseStructure Proxy
    {
      get
      {
        if( _proxy == null || _proxy.State == CommunicationState.Closed || _proxy.State == CommunicationState.Faulted ||
            _proxy.State == CommunicationState.Closing )
          lock( _proxyAccess )
            if( _proxy == null || _proxy.State == CommunicationState.Closed || _proxy.State == CommunicationState.Faulted ||
                _proxy.State == CommunicationState.Closing )
              _proxy = new EManWCFClient();
				return _proxy.EMan;
      }
    }

    public static EManServiceProxy Create()
    {
      return TypeAccessor< EManServiceProxy >.CreateInstanceEx();
    }
  }
}